package com.jy.fxf_phone.utils;

import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by JY on 2016/11/22.
 */
public class BGMPlay implements MediaPlayer.OnCompletionListener {

    MediaPlayer player;
    List<String> musics;
    int index = 0;
    int filename = 0;
    public static final String BGM_01 = "http://7xscpv.com1.z0.glb.clouddn.com/Jordy-Des%20Cadeaux%20Pour%20Noel.mp3";
    public static final String BGM_02 = "http://7xscpv.com1.z0.glb.clouddn.com/Jordy-Ma%20petite%20soeur.mp3";
    public static final String BGM_03 = "http://7xscpv.com1.z0.glb.clouddn.com/Jordy-Dur%20Dur%20D%27e%CC%82tre%20Be%CC%81be%CC%81.mp3";
    public static final String BGM_04 = "http://7xscpv.com1.z0.glb.clouddn.com/Jordy-Dis%20Tino.mp3";
    public static final String BGM_05 = "http://7xscpv.com1.z0.glb.clouddn.com/Jordy-Alison.mp3";
    public static final String[] URLS = {BGM_01, BGM_02, BGM_03, BGM_04, BGM_05};
    Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    String path = (String) msg.obj;
                    musics.add(path);
                    Log.d("handler", "handleMessage: " + musics.toArray().toString() + "isPlaying:" + player.isPlaying());
                    if (!player.isPlaying()) {
                        startSound();
                    }
                    break;
            }
            return false;
        }
    });

    private static BGMPlay ourInstance = new BGMPlay();

    public static BGMPlay getInstance() {
        return ourInstance;
    }

    private BGMPlay() {
        musics = new ArrayList<>();
        player = new MediaPlayer();
        player.setOnCompletionListener(BGMPlay.this);
    }

    public void startSound() {
        if (musics.size() == 0) {
            downloadMusic();
            return;
        }
        try {
            player.reset();
            player.setDataSource(musics.get(index));
            player.prepare();
            player.start();
            index++;
            if (index > 4) {
                index = 0;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
        }

    }


    public void stopSound() {
        if (player.isPlaying()) {
            player.stop();
        }
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        try {
            player.reset();
            player.setDataSource(musics.get(index));
            player.prepare();
            player.start();
            index++;
            if (index > 4) {
                index = 0;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void downloadMusic() {
        for (String url : URLS) {
            FileDownloader.getImpl().create(url)
                    .setListener(queueTarget)
                    .setPath("/storage/emulated/0/Android/data/com.jy.fxf_phone/cache/" + filename + ".mp3")
                    .ready();
            filename++;
        }
        FileDownloader.getImpl().start(queueTarget, false);
    }


    FileDownloadListener queueTarget = new FileDownloadListener() {
        @Override
        protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
        }

        @Override
        protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
            Log.d("download", "connected: " + "连接到服务器，开始下载" + task.getPath());
        }

        @Override
        protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            Log.d("download", "progress: " + "已下载:" + soFarBytes + " 总大小:" + totalBytes);
        }

        @Override
        protected void blockComplete(BaseDownloadTask task) {
        }

        @Override
        protected void retry(final BaseDownloadTask task, final Throwable ex, final int retryingTimes, final int soFarBytes) {
        }

        @Override
        protected void completed(BaseDownloadTask task) {
            Message message = mHandler.obtainMessage(0, task.getPath());
            mHandler.sendMessage(message);
            Log.d("download", "completed: " + task.getPath());
        }

        @Override
        protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
        }

        @Override
        protected void error(BaseDownloadTask task, Throwable e) {
        }

        @Override
        protected void warn(BaseDownloadTask task) {
        }
    };

}
